<!-- template.html -->
<div class="filter-container">
    <div class="filter-item">
        <label for="meterSelect">选择电表：</label>
        <select id="meterSelect"></select>
    </div>
    <div class="filter-item">
        <label for="dataType">数据类型：</label>
        <select id="dataType">
            <option value="u">电压</option>
            <option value="i">电流</option>
            <option value="q">功率因素</option>
            <option value="w">电量</option>
        </select>
    </div>
    <div class="filter-item">
        <label for="startDate">开始时间：</label>
        <input type="datetime-local" id="startDate">
    </div>
    <div class="filter-item">
        <label for="endDate">结束时间：</label>
        <input type="datetime-local" id="endDate">
    </div>
    <div class="filter-item">
        <button onclick="updateChart()">更新图表</button>
    </div>
</div>
<canvas id="myChart"></canvas>

<style>
.filter-container {
    display: flex;
    gap: 15px;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap; /* 如果空间不足会自动换行 */
}

.filter-item {
    display: flex;
    align-items: center;
    gap: 5px;
}

/* 调整按钮样式 */
button {
    padding: 5px 15px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #45a049;
}

/* 调整选择框和输入框样式 */
select, input[type="datetime-local"] {
    padding: 5px;
    border: 1px solid #ddd;
    border-radius: 4px;
}
</style>



<script src="/static/js/chart.umd.js"></script>
<script>
let myChart;

// 获取电表列表
function fetchMeterList() {
    return fetch('/electricity_meter_list/')
        .then(response => {
            if (!response.ok) throw new Error('网络响应不正常');
            return response.json();
        })
        .then(data => {
            const select = document.getElementById('meterSelect');
            select.innerHTML = '';

            // 添加默认选项
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = '--请选择电表--';
            select.appendChild(defaultOption);

            // 添加电表选项
            data.forEach(meter => {
                const option = document.createElement('option');
                option.value = meter.id;
                option.textContent = meter.name;
                select.appendChild(option);
            });

            return data;
        })
        .catch(error => {
            console.error('获取电表列表失败:', error);
            document.getElementById('meterSelect').innerHTML = `
                <option value="">加载电表列表失败</option>
            `;
            return [];
        });
}

function createChart(labels, data, dataType) {
    const ctx = document.getElementById('myChart').getContext('2d');

    // 根据数据类型设置图表标签
    const labelMap = {
        'u': '电压 (V)',
        'i': '电流 (A)',
        'q': '功率因素 (avr)',
        'w': '电量 (kw/h)'
    };

    myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: labelMap[dataType] || '数据趋势',
                data: data,
                borderColor: 'rgb(75, 192, 192)',
                tension: 0.1
            }]
        },
        options: {
            scales: {
                y: {
                    title: {
                        display: true,
                        text: labelMap[dataType] || '数值'
                    }
                },
                x: {
                    title: {
                        display: true,
                        text: '时间'
                    }
                }
            }
        }
    });
}

function updateChart() {
    const meterId = document.getElementById('meterSelect').value;
    if (!meterId) {
        alert('请先选择电表');
        return;
    }

    const dataType = document.getElementById('dataType').value;
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;

    fetch(`/chart_electricity/?meter_id=${meterId}&start_date=${startDate}&end_date=${endDate}`)
        .then(response => {
            if (!response.ok) throw new Error('获取图表数据失败');
            return response.json();
        })
        .then(data => {
            if (myChart) myChart.destroy();
            // 根据选择的数据类型获取对应的数据
            const chartData = data[dataType] || [];
            createChart(data.labels, chartData, dataType);
        })
        .catch(error => {
            console.error('更新图表失败:', error);
            alert('更新图表失败: ' + error.message);
        });
}

function formatDateTime(date) {
    const pad = num => String(num).padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}

// 初始加载
window.onload = function() {
    const now = new Date();
    const todayStart = new Date(now);
    todayStart.setHours(0, 0, 0, 0);

    document.getElementById('startDate').value = formatDateTime(todayStart);
    document.getElementById('endDate').value = formatDateTime(now);

    fetchMeterList().then(data => {
        if (data.length > 0) {
            // 自动选择第一个电表（跳过默认选项）
            document.getElementById('meterSelect').selectedIndex = 1;
            updateChart();
        }
    });
};
</script>